package com.liveinstars.common.sort;

import com.liveinstars.common.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * Created by guoyanjiang on 2019-01-25.
 */
public interface BaseCompareBean {

    Logger logger = LoggerFactory.getLogger(BaseCompareBean.class);

    default Comparable tryBestToFindCompareValue(String fieldName) {
        Comparable value = tryBestToFindFieldValue(fieldName, Comparable.class);
        if (value instanceof String) {
            //有一些数值在响应报文里用的String，为了避免String.compare的影响，尝试转BigDecimal进行比较，若value不是数值，则依旧用原值比较
            try {
                return new BigDecimal(value.toString().trim().replaceAll(",", "").replaceAll("%", ""));
            } catch (Exception e) {
                logger.error("排序时String类型转换为BigDecimal类型失败 原始值 {}", value);
            }
        }
        return value;
    }

    /**
     * @param fieldName 支持snake风格，可自动转换为驼峰风格再取值；若失败，会尝试用蛇形风格直接取值
     * @return
     */
    default <T> T tryBestToFindFieldValue(String fieldName, Class<T> c) {
        //因为传入的排序字段为snake风格
        String humpName = StrUtil.toHumpStr(fieldName);
        try {
            return simpleFindFieldValue(humpName, c);
        } catch (Exception e) {
            try {
                return simpleFindFieldValue(fieldName, c);
            } catch (Exception e2) {
                Comparable<T> comparable = o -> 0;
                return (T) comparable;
            }
        }
    }

    /**
     * 简单获取指定属性名的属性值
     *
     * @param fieldName
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    default <T> T simpleFindFieldValue(String fieldName, Class<T> c) throws IllegalAccessException {
        Field field = ReflectionUtils.findField(getClass(), fieldName);
        field.setAccessible(true);
        return c.cast(field.get(this));
    }
}
